<?php
namespace app\common\model;
use think\Db;
/**
 * 订单模型
 */
class Order extends Base {
	protected $pk = 'orderId';
	/**
	 * 分页-获取买家订单
	 * $type 1:待发货订单 2：待自提订单-先不考虑自提订单了
   * $orderStatus  -3：买家拒收 -2：待付款 -1：系统取消未支付订单 0：待发货 1：已发货订单 2：确认收货已完成订单
	 */
  public function pageQuery($orderStatus='', $type=0){
    $userId = (int)session('ZHT_USER.userId');
		$payType = input('payType',-1);
		$deliverType = input('deliverType',-1);
		$isRefund = input('isRefund',-1); // 是否退款
    // if($type>0){
		// 	$deliverType = ($type==1)?0:1;
		// }
		$orderNo = input('orderNo');
		$shopTitle = input('shopTitle');
		$where[] = ['o.dataFlag','=',1];
    $where[] = ['o.userId','=',$userId];
    if($payType != -1)$where[] = ['o.payType','=',$payType];
    if($deliverType != -1)$where[] = ['o.deliverType','=',$deliverType];
    if($isRefund != -1)$where[] = ['o.isRefund','=',$isRefund];
		if($orderNo != '')$where[] = ['o.orderNo','like','%'.$orderNo.'%'];
		if($shopTitle != '')$where[] = ['s.shopTitle','like','%'.$shopTitle.'%'];
		if($orderStatus != ''){
			if(is_array($orderStatus)){
				$where[] = ['o.orderStatus','in',$orderStatus];
			}else{
				$where[] = ['o.orderStatus','=',$orderStatus];
			}
		}
    
		$rs = $this->alias('o')
			->join('__SHOP__ s','o.shopId=s.shopId','left')
			->join('__ORDER_REFUND__ or','or.orderId=o.orderId and or.refundStatus!=-1','left')
      ->field('o.*,s.shopTitle,s.shopQQ,s.shopWangWang,s.shopTel,or.refundId')
			->where($where)
			->order('o.orderId', 'desc')
			->paginate(6,false,['query' => request()->param()])
			->each(function($item, $key){
				// 只要是已支付的，并且没有退款的，都可以申请退款操作
				$item['allowRefund'] = 0;
				if($item['payType']==1 && $item['isRefund']==0 && $item['refundId']=='' && $item['isPay'] ==1){
					$item['allowRefund'] = 1;
				}
        // 订单商品列表
        $goods = Db::name('order_goods')->where('orderId',$item['orderId'])->select();
        foreach ($goods as &$v){
          $v['goodsSpecTitles'] = str_replace('@@_@@','、',$v['goodsSpecTitles']);
        }
        $item['goods'] = $goods;
        // 支付方式
        $item['payTypeTitle'] = ZHTData(5,$item['payType'])['dataTitle'];
        // 配送方式
        $item['deliverTypeTitle'] = ZHTData(6,$item['deliverType'])['dataTitle'];
        $orderExpress = Db::name('order_express')->where(['orderId'=>$item['orderId']])->find();
        if(!empty($orderExpress)){
          $item['isDeliver'] = 1;
          $item['hasExpress'] = $orderExpress['isExpress'];
        }else{
          $item['isDeliver'] = 0;
          $item['hasExpress'] = 0;
        }
        // 订单状态
        $item['orderStatusTitle'] = ZHTData(7,$item['orderStatus'])['dataTitle'];
				// 未支付订单，生成加密订单号
				if($item["orderStatus"]==-2){
					$item['pkey'] = ZHTBase64urlEncode($item["orderNo"]."@0");
				}
        return $item;
			});
		return $rs;
	}
	/**
	 * 获取指定id信息
	 */
	public function getById($id){
    $userId = (int)session('ZHT_USER.userId');
    $where[] = ['o.dataFlag','=',1];
    $where[] = ['o.userId','=',$userId];
    $where[] = ['o.orderId','=',$id];
    $rs = Db::name('order')->alias('o')
      ->join('__SHOP__ s','o.shopId=s.shopId','left')
			->join('__ORDER_REFUND__ or','or.orderId=o.orderId','left')
      ->field('o.*,s.shopTitle,s.shopQQ,s.shopWangWang,s.shopTel,or.refundId,or.refundRemark,or.refundStatus,or.refundTime,or.backMoney,or.backMoney')
      ->where($where)
      ->find();
    //获取订单信息
		$log = Db::name('log_order')->where('orderId',$id)->order('logId asc')->select();
		$rs['log'] = [];
		$logFilter = [];
		foreach ($log as $key => $v) {
			if(in_array($rs['orderStatus'],[-2,0,1,2]) && in_array($v['orderStatus'],$logFilter))continue;
			$rs['log'][] = $v;
			$logFilter[] = $v['orderStatus'];
		}
    // 支付方式
    $rs['payTypeTitle'] = ZHTData(5,$rs['payType'])['dataTitle'];
    // 配送方式
    $rs['deliverTypeTitle'] = ZHTData(6,$rs['deliverType'])['dataTitle'];
		// 只要是已支付的，并且没有退款的，都可以申请退款操作
		$rs['allowRefund'] = 0;
		if($rs['payType']==1 && $rs['isRefund']==0 && $rs['refundId']=='' && $rs['isPay'] ==1){
			$rs['allowRefund'] = 1;
		}
    // 订单商品列表
    $goods = Db::name('order_goods')->alias('og')
      ->join('__GOODS__ g','g.goodsId=og.goodsId','left')
      ->where('orderId',$id)
      ->field('og.*,g.goodsSn')
      ->order('id asc')
      ->select();
    foreach ($goods as &$v){
      $v['goodsSpecTitles'] = str_replace('@@_@@','、',$v['goodsSpecTitles']);
    }
    $rs['goods'] = $goods;
    // 发货时间与快递单号
    $orderExpressNos = Db::name('order_express')->where([['orderId','=',$id],['isExpress','=',1]])->column("expressNo");
    if($orderExpressNos){
      // 多张快递单号用逗号拼接，并过滤掉没有单号的
      $rs["expressNo"] = implode(",",array_filter($orderExpressNos));
    }else{
      $rs["expressNo"] = '';
    }
		return $rs;
	}
	/**
	* 用户-提醒发货
	*/
	public function noticeDeliver(){
		$orderId = (int)input('id');
		// hook("beforeOrderNoticeDeliver",['uId'=>$uId,'orderId'=>$orderId]);
		$userId = (int)session('ZHT_USER.userId');
		Db::startTrans();
		try{
			$rs = $this->where(['userId'=>$userId,'orderId'=>$orderId])->setField('noticeDeliver',1);
			// if($rs!==false){
			// 	$info = $this->alias('o')->field('shopId,orderNo')->where(['userId'=>$userId,'orderId'=>$orderId])->find();
			// 	//发送商城消息提醒卖家
			// 	$tpl = ZHTMsgTemplates('ORDER_REMINDER');
      //           if( $tpl['tplContent']!='' && $tpl['status']=='1'){
      //               $find = ['${LOGIN_NAME}','${ORDER_NO}'];
      //               $replace = [session('ZHT_USER.loginName'),$info['orderNo']];

      //               $msg = array();
		  //           $msg["shopId"] = $info['shopId'];
		  //           $msg["tplCode"] = $tpl["tplCode"];
		  //           $msg["msgType"] = 1;
		  //           $msg["content"] = str_replace($find,$replace,$tpl['tplContent']);
		  //           $msg["msgJson"] = [];
		  //           model("common/MessageQueues")->add($msg);
      //           }
			// }
			Db::commit();
			return ZHTReturn('提醒成功',1);
		}catch(\Exception $e){
			Db::rollback();
		}
		return ZHTReturn('提醒失败',-1);
	}
	/**
	 * 用户收货[同时给外部虚拟商品收货调用]
	 * 注意：修改该函数的逻辑，要留意一同修改管理员修改订单的函数逻辑[admin/model/order->receiveOrder]
	 */
	public function receive($orderId = 0, $userId = 0){
		if ($orderId == 0 && $userId == 0) {
			$orderId = (int)input('post.id');
			$userId = (int)session('ZHT_USER.userId');
		}
		// hook("beforeUserReceive", ["orderId" => $orderId, "userId" => $userId]);
		$order = $this->alias('o')->join('__SHOP__ s', 'o.shopId=s.shopId', 'left')
		->where(['o.userId' => $userId, 'o.orderId' => $orderId, 'o.orderStatus' => 1])
			->field('o.orderId,o.orderNo,o.payType,s.userId,s.shopId,o.orderScore,o.realTotalMoney,commissionFee,o.create_time')->find();
		if (!empty($order)) {
			Db::startTrans();
			try {
				$limitDay = (int)ZHTConf('CONF.afterSaleServiceDays');
				// 售后结束时间
				$afterSaleEndTime = date('Y-m-d H:i:s', strtotime("+{$limitDay} day"));
				$data = ['orderStatus' => 2, 'receiveTime' => date('Y-m-d H:i:s'), 'afterSaleEndTime' => $afterSaleEndTime];
				$result = $this->where('orderId', $order['orderId'])->update($data);
				if (false != $result) {
					//修改商品成交量
					$goodss = Db::name('order_goods')->where('orderId', $order['orderId'])->field('goodsId,goodsNum,goodsSpecId')->select();
					foreach ($goodss as $key => $v) {
						Db::name('goods')->where('goodsId', $v['goodsId'])->update([
							'saleNum' => Db::raw('saleNum+' . $v['goodsNum'])
						]);
						if ($v['goodsSpecId'] > 0) {
							Db::name('goods_spec')->where('id', $v['goodsSpecId'])->update([
								'saleNum' => Db::raw('saleNum+' . $v['goodsNum'])
							]);
						}
					}

					//确认收货后执行钩子
					// hook('afterUserReceive', ['orderId' => $orderId]);
					//修改商家未计算订单数
					$torder = Db::name('order')->where("orderId", $orderId)->field("orderId,commissionFee")->find();
					Db::name('shop')->where('shopId', $order['shopId'])->update([
						'noSettledOrderNum' => Db::raw('noSettledOrderNum+1'),
						'noSettledOrderFee' => Db::raw('noSettledOrderFee-' . $torder['commissionFee'])
					]);
					//新增订单日志
					$logOrder = [];
					$logOrder['orderId'] = $orderId;
					$logOrder['orderStatus'] = 2;
					$logOrder['logContent'] = "用户已收货";
					$logOrder['logUserId'] = $userId;
					$logOrder['logType'] = 0;
					$logOrder['logTime'] = time();
					Db::name('log_order')->insert($logOrder);
					//标记会员在这个商家下已下单，有则标记，没有数据也不影响
					// Db::name('shop_members')->where(['userId' => $userId, 'shopId' => $order["shopId"]])->update(['isOrder' => 1, 'totalOrderNum' => DB::Raw('totalOrderNum+1'), 'totalOrderMoney' => DB::Raw('totalOrderMoney+' . $order['realTotalMoney']), 'lastOrderTime' => $order['createTime']]); // 注意这个时间是时间戳，要转成时间格式
					// $shopMember = model('common/ShopMembers')->checkIsShopMember($userId, $order["shopId"]);
					// if ($shopMember) {
					// 	// 计算用户在店铺有效的消费金额
					// 	ZHTCalcUserValidConsumption($userId, $order["shopId"]);
					// 	// 更新用户的会员等级
					// 	$groupId = ZHTGetMemberGroupId($userId, $order["shopId"]);
					// 	if ($groupId > 0) {
					// 		$member = Db::name('shop_members')->where(['userId' => $userId, 'shopId' => $order["shopId"]])->find();
					// 		if ($member['groupId'] != $groupId) {
					// 			Db::name('shop_members')->where(['userId' => $userId, 'shopId' => $order["shopId"]])->update(['groupId' => $groupId]);
					// 		}
					// 	}
					// }
					//发送一条商家信息
					// $tpl = ZHTMsgTemplates('ORDER_RECEIVE');
					// if ($tpl['tplContent'] != '' && $tpl['status'] == '1') {
					// 	$find = ['${ORDER_NO}'];
					// 	$replace = [$order['orderNo']];

					// 	$msg = array();
					// 	$msg["shopId"] = $order["shopId"];
					// 	$msg["tplCode"] = $tpl["tplCode"];
					// 	$msg["msgType"] = 1;
					// 	$msg["content"] = str_replace($find, $replace, $tpl['tplContent']);
					// 	$msg["msgJson"] = ['from' => 1, 'dataId' => $orderId];
					// 	model("common/MessageQueues")->add($msg);
					// }

					//给用户增加积分
					if (ZHTConf("CONF.isOrderScore") == 1 && $order['orderScore'] > 0) {
						$score = [];
						$score['userId'] = $userId;
						$score['score'] = $order['orderScore'];
						$score['dataSrc'] = 1;
						$score['dataId'] = $orderId;
						$score['dataRemarks'] = "交易订单【" . $order['orderNo'] . "】获得积分" . $order['orderScore'] . "个";
						$score['scoreType'] = 1;
						model('user_score')->add($score, true);
					}
					//微信消息
					// if ((int)ZHTConf('CONF.wxenabled') == 1) {
					// 	$params = [];
					// 	$params['ORDER_NO'] = $order['orderNo'];
					// 	$params['ORDER_TIME'] = date('Y-m-d H:i:s');
					// 	//ZHTWxMessage(['CODE'=>'WX_ORDER_RECEIVE','userId'=>$order['userId'],'URL'=>Url('wechat/order/sellerorder','',true,true),'params'=>$params]);
					// 	$msg = array();
					// 	$tplCode = "WX_ORDER_RECEIVE";
					// 	$msg["shopId"] = $order["shopId"];
					// 	$msg["tplCode"] = $tplCode;
					// 	$msg["msgType"] = 4;
					// 	$msg["paramJson"] = ['CODE' => $tplCode, 'URL' => Url('wechat/order/sellerorder', '', true, true), 'params' => $params];
					// 	$msg["msgJson"] = "";
					// 	model("common/MessageQueues")->add($msg);
					// }
					Db::commit();
					return ZHTReturn('操作成功', 1);
				}
			} catch (\Exception $e) {
				Db::rollback();
				return ZHTReturn('操作失败' . $e->getMessage(), -1);
			}
		}
		return ZHTReturn('操作失败，请检查订单状态是否已改变');
	}
	/**
	 * 用户取消订单
	 * 注意：修改该函数的逻辑，要留意一同修改管理员修改订单的函数逻辑[admin/model/orders->cancelOrder]
	 */
	public function cancel($uId = 0){
		$orderId = (int)input('post.id');
		// hook('beforeCancelOrder', ['uId' => $uId, 'orderId' => $orderId]);
		$reason = (int)input('post.reason');
		$userId = ($uId == 0) ? (int)session('ZHT_USER.userId') : $uId;
		$order = $this->alias('o')->join('__SHOP__ s', 'o.shopId=s.shopId', 'left')
		->where([['o.orderStatus', 'in', [-2, 0]], ['o.userId', '=', $userId], ['o.orderId', '=', $orderId]])
			->field('o.orderId,o.orderNo,s.userId,s.shopId,o.orderCode,o.isPay,o.orderType,o.payType,o.orderStatus,o.useScore,o.scoreMoney,o.realTotalMoney')->find();
		$reasonData = ZHTData(8, $reason);
		if (empty($reasonData)) return ZHTReturn("无效的取消原因");

		if (!empty($order)) {
			Db::startTrans();
			try {
				$data = ['orderStatus' => -1, 'cancelReason' => $reason];
				//把实付金额设置为0
				if ($order['payType'] == 0 || ($order['payType'] == 1 && $order['isPay'] == 0)) {
					$data['realTotalMoney'] = 0;
					$order['realTotalMoney'] = 0;
					$data['isClosed'] = 1;
				}
				$result = $this->where('orderId', $order['orderId'])->update($data);
				if (false != $result) {
					//正常订单商品库存处理
					$goods = Db::name('order_goods')->alias('og')->join('__GOODS__ g', 'og.goodsId=g.goodsId', 'inner')
					->where('orderId', $orderId)->field('og.*,g.isSpec')->select();
					//返还商品库存
					foreach ($goods as $key => $v) {
						//处理虚拟产品
						if ($v['goodsType'] == 1) {
							$extraJson = json_decode($v['extraJson'], true);
							foreach ($extraJson as  $ecard) {
								Db::name('goods_virtuals')->where('id', $ecard['cardId'])->update(['orderId' => 0, 'orderNo' => '', 'isUse' => 0]);
							}
							$counts = Db::name('goods_virtuals')->where(['dataFlag' => 1, 'goodsId' => $v['goodsId'], 'isUse' => 0])->count();
							Db::name('goods')->where('goodsId', $v['goodsId'])->setField('goodsStock', $counts);
						} else {
							if ($order['orderCode'] == 'order') {
								//修改库存
								if ($v['isSpec'] > 0) {
									Db::name('goods_spec')->where('id', $v['goodsSpecId'])->setInc('specStock', $v['goodsNum']);
								}
								Db::name('goods')->where('goodsId', $v['goodsId'])->setInc('goodsStock', $v['goodsNum']);
							}
						}
					}
					//新增订单日志
					$logOrder = [];
					$logOrder['orderId'] = $orderId;
					$logOrder['orderStatus'] = -1;
					$logOrder['logContent'] = "用户取消订单，取消原因：" . $reasonData['dataTitle'];
					$logOrder['logUserId'] = $userId;
					$logOrder['logType'] = 0;
					$logOrder['logTime'] = time();
					Db::name('log_order')->insert($logOrder);
					//提交订单后执行钩子
					// hook('afterCancelOrder', ['orderId' => $orderId]);
					//发送一条商家信息
					// $tpl = ZHTMsgTemplates('ORDER_CANCEL');
					// if ($tpl['tplContent'] != '' && $tpl['status'] == '1') {

					// 	$find = ['${ORDER_NO}', '${REASON}'];
					// 	$replace = [$order['orderNo'], $reasonData['dataTitle']];

					// 	$msg = array();
					// 	$msg["shopId"] = $order["shopId"];
					// 	$msg["tplCode"] = $tpl["tplCode"];
					// 	$msg["msgType"] = 1;
					// 	$msg["content"] = str_replace($find, $replace, $tpl['tplContent']);
					// 	$msg["msgJson"] = ['from' => 1, 'dataId' => $orderId];
					// 	model("common/MessageQueues")->add($msg);
					// }
					//判断是否需要发送商家短信
					// $tpl = ZHTMsgTemplates('PHONE_SHOP_CANCEL_ORDER');
					// if ((int)ZHTConf('CONF.smsOpen') == 1 && $tpl['tplContent'] != '' && $tpl['status'] == '1') {

					// 	$params = ['tpl' => $tpl, 'params' => ['ORDER_NO' => $order['orderNo']]];

					// 	$msg = array();
					// 	$tplCode = "PHONE_SHOP_CANCEL_ORDER";
					// 	$msg["shopId"] = $order["shopId"];
					// 	$msg["tplCode"] = $tplCode;
					// 	$msg["msgType"] = 2;
					// 	$msg["paramJson"] = ['CODE' => $tplCode, 'method' => 'cancel', 'params' => $params];
					// 	$msg["msgJson"] = "";
					// 	model("common/MessageQueues")->add($msg);
					// }
					//微信消息
					// if ((int)ZHTConf('CONF.wxenabled') == 1) {
					// 	$params = [];
					// 	$params['ORDER_NO'] = $order['orderNo'];
					// 	$goodsNames = [];
					// 	foreach ($goods as $gkey => $g) {
					// 		$goodsNames[] = $g['goodsName'] . "*" . $g['goodsNum'];
					// 	}
					// 	$params['REASON'] = $reasonData['dataTitle'];
					// 	$params['GOODS'] = implode(',', $goodsNames);
					// 	$params['MONEY'] = $order['realTotalMoney'] + $order['scoreMoney'];

					// 	$msg = array();
					// 	$tplCode = "WX_ORDER_CANCEL";
					// 	$msg["shopId"] = $order["shopId"];
					// 	$msg["tplCode"] = $tplCode;
					// 	$msg["msgType"] = 4;
					// 	$msg["paramJson"] = ['CODE' => 'WX_ORDER_CANCEL', 'URL' => Url('wechat/orders/sellerorder', '', true, true), 'params' => $params];
					// 	$msg["msgJson"] = "";
					// 	model("common/MessageQueues")->add($msg);
					// }

					Db::commit();
					return ZHTReturn('订单取消成功', 1);
				}
			} catch (\Exception $e) {
				Db::rollback();
				return ZHTReturn('操作失败', -1);
			}
		}
		return ZHTReturn('操作失败，请检查订单状态是否已改变');
	}
	/**
	 * 用户拒收订单
	 */
	public function reject($uId = 0)	{
		$orderId = (int)input('post.id');
		// hook('beforeRejectOrder', ['uId' => $uId, 'orderId' => $orderId]);
		$reason = (int)input('post.reason');
		$content = input('post.content');
		$userId = ($uId == 0) ? (int)session('ZHT_USER.userId') : $uId;
		$order = $this->alias('o')->join('__SHOP__ s', 'o.shopId=s.shopId', 'left')
		->where(['o.userId' => $userId, 'o.orderId' => $orderId, 'o.orderStatus' => 1])
			->field('o.orderId,o.orderNo,o.shopId,s.userId,payType,o.userAddress,o.userName,o.realTotalMoney,o.scoreMoney')->find();
		$reasonData = ZHTData(9, $reason);
		if (empty($reasonData)) return ZHTReturn("无效的拒收原因");
		if ($reason == 10000 && $content == '') return ZHTReturn("请输入拒收原因");
		if (!empty($order)) {
			Db::startTrans();
			try {
				$data = ['orderStatus' => -3, 'rejectReason' => $reason];
				if ($reason == 10000) $data['rejectOtherReason'] = $content;
				//如果是货到付款拒收的话，把实付金额设置为0
				if ($order['payType'] == 0) $data['realTotalMoney'] = 0;
				$result = $this->where('orderId', $order['orderId'])->update($data);
				if (false != $result) {
					//新增订单日志
					$logOrder = [];
					$logOrder['orderId'] = $orderId;
					$logOrder['orderStatus'] = -3;
					$logOrder['logContent'] = "用户拒收订单，拒收原因：" . $reasonData['dataTitle'] . (($reason == 10000) ? "-" . $content : "");
					$logOrder['logUserId'] = $userId;
					$logOrder['logType'] = 0;
					$logOrder['logTime'] = time();
					Db::name('log_order')->insert($logOrder);
					//发送一条商家信息
					// $tpl = ZHTMsgTemplates('ORDER_REJECT');
					// if ($tpl['tplContent'] != '' && $tpl['status'] == '1') {
					// 	$find = ['${ORDER_NO}', '${REASON}'];
					// 	$replace = [$order['orderNo'], $reasonData['dataTitle'] . (($reason == 10000) ? "-" . $content : "")];

					// 	$msg = array();
					// 	$msg["shopId"] = $order['shopId'];
					// 	$msg["tplCode"] = $tpl["tplCode"];
					// 	$msg["msgType"] = 1;
					// 	$msg["content"] = str_replace($find, $replace, $tpl['tplContent']);
					// 	$msg["msgJson"] = ['from' => 1, 'dataId' => $orderId];
					// 	model("common/MessageQueues")->add($msg);
					// }
					//判断是否需要发送商家短信
					// $tpl = ZHTMsgTemplates('PHONE_SHOP_REJECT_ORDER');
					// if ((int)ZHTConf('CONF.smsOpen') == 1 && $tpl['tplContent'] != '' && $tpl['status'] == '1') {

					// 	$params = ['tpl' => $tpl, 'params' => ['ORDER_NO' => $order['orderNo']]];

					// 	$msg = array();
					// 	$tplCode = "PHONE_SHOP_REJECT_ORDER";
					// 	$msg["shopId"] = $order["shopId"];
					// 	$msg["tplCode"] = $tplCode;
					// 	$msg["msgType"] = 2;
					// 	$msg["paramJson"] = ['CODE' => $tplCode, 'method' => 'reject', 'params' => $params];
					// 	$msg["msgJson"] = "";
					// 	model("common/MessageQueues")->add($msg);
					// }

					//微信消息
					// if ((int)ZHTConf('CONF.wxenabled') == 1) {
					// 	$params = [];
					// 	$params['ORDER_NO'] = $order['orderNo'];
					// 	$goods = Db::name('order_goods')->where('orderId', $order['orderId'])->select();
					// 	$goodsNames = [];
					// 	foreach ($goods as $gkey => $goods) {
					// 		$goodsNames[] = $goods['goodsName'] . "*" . $goods['goodsNum'];
					// 	}
					// 	$params['GOODS'] = implode(',', $goodsNames);
					// 	$params['MONEY'] = $order['realTotalMoney'] + $order['scoreMoney'];
					// 	$params['ADDRESS'] = $order['userAddress'] . " " . $order['userName'];
					// 	$params['REASON'] = $reasonData['dataTitle'] . (($reason == 10000) ? "-" . $content : "");

					// 	$msg = array();
					// 	$tplCode = "WX_ORDER_REJECT";
					// 	$msg["shopId"] = $order['shopId'];
					// 	$msg["tplCode"] = $tplCode;
					// 	$msg["msgType"] = 4;
					// 	$msg["paramJson"] = ['CODE' => $tplCode, 'URL' => Url('wechat/orders/sellerorder', '', true, true), 'params' => $params];
					// 	$msg["msgJson"] = "";
					// 	model("common/MessageQueues")->add($msg);
					// }
					Db::commit();
					return ZHTReturn('操作成功', 1);
				}
			} catch (\Exception $e) {
				Db::rollback();
				return ZHTReturn('操作失败', -1);
			}
		}
		return ZHTReturn('操作失败，请检查订单状态是否已改变');
	}
	/**
	 * 正常订单
	 */
	public function submit($orderSrc = 0, $uId=0){
		$addressId = (int)input('post.s_addressId');
		$deliverType = ((int)input('post.deliverType')!=0)?1:0;
		$payType = ((int)input('post.payType')!=0)?1:0;
		$userId = ($uId==0)?(int)session('ZHT_USER.userId'):$uId;
		$isUseScore = (int)input('isUseScore');
		$useScore = (int)input('useScore');
		if($userId==0)return ZHTReturn('下单失败，请先登录');
		
		//检测购物车
		$carts = model('cart')->getCart(true, $userId);
		if(empty($carts['carts']))return ZHTReturn("下单失败，请选择有效的库存商品");
		
		//检测地址是否有效
		$address = Db::name('user_address')->where(['userId'=>$userId,'addressId'=>$addressId,'dataFlag'=>1])->find();
		if(empty($address)){
			return ZHTReturn("无效的用户地址");
		}
		$areaIds = explode('_', $address['areaIdPath']);
		$address['areaId2'] = $areaIds[1]; //记录配送城市
    $areas = Db::name('area')->where([['areaId', 'in', $areaIds], ['dataFlag', '=', 1]])->column('areaName');
    $address['userAddress'] = implode('', $areas).$address['userAddress'];
		ZHTUnset($address, 'isDefault,dataFlag,userId');
		
		//计算出每个订单应该分配的金额和积分
		$orderScoreMoney = $this->allocScoreMoney($carts,$isUseScore,$useScore, $userId);
		//生成订单
		Db::startTrans();
		try{
			//提交订单前执行钩子
			// hook('beforeSubmitOrder',['carts'=>$carts,"payType"=>$payType]);
			$orderunique = ZHTOrderQnique();
			foreach ($carts['carts'] as $ckey =>$shopOrder){
				$orderNo = ZHTOrderNo();
				$orderScore = 0;
				$shopId = $shopOrder['shopId'];
				$deliverType = ((int)input('post.deliverType_'.$shopId)!=0)?1:0;

				//创建订单
				$order = [];
				$order = array_merge($order,$address);
				$order['orderNo'] = $orderNo;
				$order['userId'] = $userId;
				$order['shopId'] = $shopId;
				$order['payType'] = $payType;
				$order['goodsMoney'] = $shopOrder['goodsMoney'];
				//计算运费和总金额
				$order['deliverType'] = $deliverType;
				if($shopOrder['isFreeShipping']){
          $order['deliverMoney'] = 0;
				}else{
					$order['deliverMoney'] = ($deliverType==1)?0:ZHTOrderFreight($shopId,$order['areaId2'],$shopOrder);
				}
				if($deliverType==1){//自提
					$order['storeId'] = (int)input("storeId_".$shopId);
					$order['storeType'] = 1;
				}
				$order['totalMoney'] = $order['goodsMoney']+$order['deliverMoney'];
        //积分支付-计算分配积分和金额
        $shopOrderMoney = $orderScoreMoney[$shopId];
				$order['scoreMoney'] = $shopOrderMoney['useMoney'];
				$order['useScore'] = $shopOrderMoney['useScore'];
				//实付金额要减去积分兑换的金额和店铺总优惠
				$order['realTotalMoney'] = ZHTPositiveNum($order['totalMoney'] - $order['scoreMoney'] - $shopOrder['promotionMoney']);
				$order['needPay'] = $order['realTotalMoney'];
				if ($payType == 1) {
					if ($order['needPay'] > 0) {
						$order['orderStatus'] = -2; //待付款
						$order['isPay'] = 0;
					} else {
						$order['orderStatus'] = 0; //待发货
						$order['isPay'] = 1;
						$order['payTime'] = date('Y-m-d H:i:s');
						$order['payFrom'] = 'others';
						if ($deliverType == 1) $order['verificationCode'] = ZHTOrderVerificationCode($shopId);
					}
				} else {
					$order['orderStatus'] = 0; //待发货
					if ($order['needPay'] == 0) {
						$order['isPay'] = 1;
						$order['payFrom'] = 'others';
						$order['payTime'] = date('Y-m-d H:i:s');
					}
					if ($deliverType == 1) $order['verificationCode'] = ZHTOrderVerificationCode($shopId);
				}
				//积分
				$orderScore = 0;
				//如果开启下单获取积分则有积分
				if(ZHTConf('CONF.isOrderScore')==1){
				  $orderScore = ZHTMoneyGiftScore($order['realTotalMoney']-$order['deliverMoney']);
				}
				$order['orderScore'] = $orderScore;
				// 获得的积分可抵扣金额
				$order['getScoreVal'] = ZHTScoreToMoney($order['orderScore']);

				if($shopOrder['isInvoice']==1){
					$isInvoice = ((int)input('post.isInvoice_'.$shopId)!=0)?1:0;
					$invoiceClient = ($isInvoice==1)?input('post.invoiceClient_'.$shopId):'';
					$order['isInvoice'] = $isInvoice;
					if($isInvoice==1){
						$order['invoiceJson'] = model('invoice')->getInviceInfo((int)input('param.invoiceId_'.$shopId),$userId);// 发票信息
						$order['invoiceClient'] = $invoiceClient;
					}else{
						$order['invoiceJson'] = '';// 发票信息
						$order['invoiceClient'] = '';
					}
				}else{
					$order['isInvoice'] = 0;
					$order['invoiceJson'] = '';// 发票信息
					$order['invoiceClient'] = '';
				}

				$order['orderRemarks'] = input('post.remark_'.$shopId);
				$order['orderunique'] = $orderunique;
				$order['orderSrc'] = $orderSrc;
				$order['dataFlag'] = 1;
				$order['payRand'] = 1;
				//创建订单前执行钩子
				// hook('beforeInsertOrder',['order'=>&$order,'carts'=>$carts, 'shopOrder'=>&$shopOrder]);
				$result = $this->data($order,true)->isUpdate(false)->allowField(true)->save($order);
				if(false !== $result){
					$orderId = $this->orderId;
					$orderTotalGoods = [];
					$commissionFee = 0;
					
					/**
					 * 计算订单中的商品可优惠多少金额
					 */
					// 1.先计算出商品总价  $order['goodsMoney']为订单下的商品总价
					// 2.计算积分抵扣的金额、使用的积分、获得的积分
					// 3.计算满减活动抵扣的金额【参与满减活动的商品】
					// 4.计算优惠券抵扣的金额【参与优惠券减免的商品】

					// 商品下累计减免的积分
					$ogScore = 0;
					// 商品下累计减免的积分金额
					$ogScoreMoney = 0;
					// 订单下最后一件商品索引
					$lastOgIndex = count($shopOrder['list'])-1;
					
					foreach ($shopOrder['list'] as $gkey =>$goods){
						//创建订单商品记录
						$orderGgoods = [];
						$orderGoods['orderId'] = $orderId;
						$orderGoods['goodsId'] = $goods['goodsId'];
						$orderGoods['goodsNum'] = $goods['cartNum'];
						$orderGoods['goodsPrice'] = $goods['shopPrice'];
						$orderGoods['goodsSpecId'] = $goods['goodsSpecId'];
						if(!empty($goods['specTitles'])){
							$specNams = [];
							foreach ($goods['specTitles'] as $pkey =>$spec){
								$specNams[] = $spec['specTitle'].'：'.$spec['itemTitle'];
							}
							$orderGoods['goodsSpecTitles'] = implode('@@_@@',$specNams);
						}else{
							$orderGoods['goodsSpecTitles'] = '';
						}
						$orderGoods['goodsTitle'] = $goods['goodsTitle'];
						$orderGoods['goodsImg'] = $goods['goodsImg'];
						// return ZHTReturn('提交订单失败2',-1,['catId'=>$goods['catId']]);
						$orderGoods['commissionRate'] = ZHTGoodsCommissionRate($goods['catId']);
						
						$orderGoods['goodsCode'] = '';
						$orderGoods['goodsType'] = $goods['goodsType'];
						$orderGoods['extraJson'] = '';
						$orderGoods['promotionJson'] = '';

						/****************************************  满减活动减免的金额start  ****************************************/
						// 在插件钩子内完成金额计算
						/****************************************  满减活动减免的金额end  ****************************************/

						/****************************************  优惠券减免的金额start  ****************************************/
						if(isset($goods['couponVal']))$orderGoods['couponVal'] = $goods['couponVal'];
						/****************************************  优惠券减免的金额end  ****************************************/


						/****************************************  积分抵扣的金额start  ****************************************/
						$rate = $goods['shopPrice']*$goods['cartNum']/$order['goodsMoney'];
						if((int)ZHTConf('CONF.isOpenScorePay')==1){// 后台有开启积分支付
							// 该订单总共使用的积分->$order['useScore'] 积分可抵扣的金额->$order['scoreMoney']
							if($lastOgIndex===$gkey){// 最后一件商品
								// 最后一件商品的使用积分=订单使用积分-同订单下其他商品使用积分的总和;积分减免金额同理
								$orderGoods['useScoreVal'] = $order['useScore']-$ogScore;
								$orderGoods['scoreMoney'] = $order['scoreMoney']-$ogScoreMoney;
							}else{
								// 使用的积分数;执行向下取整【余下部分会在计算最后一件商品时加上】
								$orderGoods['useScoreVal'] = floor($rate*$order['useScore']);
								$ogScore += $orderGoods['useScoreVal'];
								// 订单商品的积分减免金额 = (商品价格*购买数量/商品总价格)*订单积分减免金额;保留小数点后两位
								$orderGoods['scoreMoney'] = round(ZHTScoreToMoney($orderGoods['useScoreVal']), 2);
								$ogScoreMoney += $orderGoods['scoreMoney'];
							}
						}
						//如果开启下单获取积分则有积分
						// $orderGoods['getScoreVal'] = 0;
						if(ZHTConf('CONF.isOrderScore')==1){
							$orderGoods['getScoreVal'] = ZHTMoneyGiftScore($goods['shopPrice']*$goods['cartNum']);
							// 获得的积分可抵扣金额
							$orderGoods['getScoreMoney'] = ZHTScoreToMoney($orderGoods['getScoreVal']);
						}
						/****************************************  积分抵扣的金额end  ****************************************/
						$orderGoods["orderGoodscommission"] = 0;
						//计算订单总佣金
						if((float)$orderGoods['commissionRate']>0){
							$orderGoodscommission = round($orderGoods['goodsPrice']*$orderGoods['goodsNum']*$orderGoods['commissionRate']/100,2);
							$orderGoods["orderGoodscommission"] = $orderGoodscommission;
							$commissionFee += $orderGoodscommission;
						}
						$orderTotalGoods[] = $orderGoods;

						//修改库存
						if($goods['goodsSpecId']>0){
					    Db::name('goods_spec')->where('id',$goods['goodsSpecId'])->update(['specStock'=>Db::raw('specStock-'.$goods['cartNum'])]);
						}
            Db::name('goods')->where('goodsId',$goods['goodsId'])->update(['goodsStock'=>Db::raw('goodsStock-'.$goods['cartNum'])]);
					}
					//创建订单商品前执行钩子
					// hook('beforeInsertOrderGoods',['orderId'=>$orderId,'orderGoods'=>&$orderTotalGoods,'carts'=>$carts]);
					Db::name('order_goods')->insertAll($orderTotalGoods);
					//更新订单佣金
					$this->where('orderId',$orderId)->update(['commissionFee'=>$commissionFee]);
					//提交订单后执行钩子
					// hook('afterSubmitOrder',['orderId'=>$orderId]);

					//创建积分流水--如果有抵扣积分就肯定是开启了支付支付
					if($order['useScore']>0){
						$score = [];
						$score['userId'] = $userId;
						$score['score'] = $order['useScore'];
						$score['dataSrc'] = 1;
						$score['dataId'] = $orderId;
						$score['dataRemarks'] = "交易订单【".$orderNo."】使用积分".$order['useScore']."个";
						$score['scoreType'] = 0;
						model('user_score')->add($score);
					}

					//建立订单记录
					$logOrder = [];
					$logOrder['orderId'] = $orderId;
					$logOrder['orderStatus'] = ($payType==1 && $order['needPay']==0)?-2:$order['orderStatus'];
					$logOrder['logContent'] = ($payType==1)?"下单成功，等待用户支付":"下单成功";
					$logOrder['logUserId'] = $userId;
					$logOrder['logType'] = 0;
					$logOrder['logTime'] = time();
					Db::name('log_order')->insert($logOrder);
					if($payType==1 && $order['needPay']==0){
						$logOrder = [];
						$logOrder['orderId'] = $orderId;
						$logOrder['orderStatus'] = 0;
						$logOrder['logContent'] = "订单已支付，下单成功";
						$logOrder['logUserId'] = $userId;
						$logOrder['logType'] = 0;
						$logOrder['logTime'] = time();
						Db::name('log_order')->insert($logOrder);
					}
				// 	if($deliverType==1){//自提
				// 		//自提订单（已支付）发送核验码
				// 		if(($payType==1 && $order['needPay']==0) || $payType==0){
				// 			$tpl = ZHTMsgTemplates('PHONE_USER_ORDER_VERIFICATCODE');
				// 	        if( $tpl['tplContent']!='' && $tpl['status']=='1'){
				// 	        	$userPhone = $order['userPhone'];
				// 	        	$storeId = $order['storeId'];
				// 	        	$store = Db::name("stores")->where(["storeId"=>$storeId])->field("storeName,storeAddress")->find();
				// 	        	$storeName = $store["storeName"];
				// 	        	$storeAddress = $store["storeAddress"];
				// 	        	$splieVerificationCode = join(" ",str_split($order['verificationCode'],4));
				// 	            $params = ['tpl'=>$tpl,'params'=>['MALL_NAME'=>ZHTConf('CONF.mallName'),'ORDER_CODE'=>$splieVerificationCode,'SHOP_NAME'=>$storeName,'SHOP_ADDRESS'=>$storeAddress]];
				// 	            model("common/LogSms")->sendSMS(0,$userPhone,$params,'submit','',$userId,0);
				// 	        }
				// 		}
				//   }
				// 	//给店铺增加提示消息
				// 	$tpl = ZHTMsgTemplates('ORDER_SUBMIT');
				// 	if ($tpl['tplContent'] != '' && $tpl['status'] == '1') {
				// 		$find = ['${ORDER_NO}'];
				// 		$replace = [$orderNo];

				// 		$msg = array();
				// 		$msg["shopId"] = $shopOrder['shopId'];
				// 		$msg["tplCode"] = $tpl["tplCode"];
				// 		$msg["msgType"] = 1;
				// 		$msg["content"] = str_replace($find, $replace, $tpl['tplContent']);
				// 		$msg["msgJson"] = ['from' => 1, 'dataId' => $orderId];
				// 		model("common/MessageQueues")->add($msg);
				// 	}
				// 	//判断是否需要发送商家短信
		    //   $tpl = ZHTMsgTemplates('PHONE_SHOP_SUBMIT_ORDER');
				// 	if((int)ZHTConf('CONF.smsOpen')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
				// 		$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$orderNo]];
				// 		$msg = array();
				// 		$tplCode = "PHONE_SHOP_SUBMIT_ORDER";
				// 		$msg["shopId"] = $shopOrder['shopId'];
				// 		$msg["tplCode"] = $tplCode;
				// 		$msg["msgType"] = 2;
				// 		$msg["paramJson"] = ['CODE'=>$tplCode,'method'=>'submit','params'=>$params];
				// 		$msg["msgJson"] = "";
				// 		model("common/MessageQueues")->add($msg);
				// 	}
				// 	//微信消息
				// 	if ((int)ZHTConf('CONF.wxenabled') == 1) {
				// 		$params = [];
				// 		$params['ORDER_NO'] = $orderNo;
				// 		$params['ORDER_TIME'] = date('Y-m-d H:i:s');
				// 		$goodsTitles = [];
				// 		foreach ($shopOrder['list'] as $gkey => $goods) {
				// 			$goodsTitles[] = $goods['goodsTitle'] . "*" . $goods['cartNum'];
				// 		}
				// 		$params['GOODS'] = implode(',', $goodsTitles);
				// 		$params['MONEY'] = $order['realTotalMoney'] + $order['scoreMoney'];
				// 		$params['ADDRESS'] = $order['userAddress'] . " " . $order['userName'];
				// 		$params['PAY_TYPE'] = ZHTLangPayType($order['payType']);

				// 		$msg = array();
				// 		$tplCode = "WX_ORDER_SUBMIT";
				// 		$msg["shopId"] = $shopOrder['shopId'];
				// 		$msg["tplCode"] = $tplCode;
				// 		$msg["msgType"] = 4;
				// 		$msg["paramJson"] = ['CODE' => $tplCode, 'URL' => Url('wechat/order/sellerorder', '', true, true), 'params' => $params];
				// 		$msg["msgJson"] = "";
				// 		model("common/MessageQueues")->add($msg);
					// }
				}
			}
			//删除已选的购物车商品
			Db::name('cart')->where(['userId'=>$userId,'isCheck'=>1])->delete();
			Db::commit();
			// hook("afterOrderPaySuccess",['orderId'=>$orderunique,'isBatch'=>1,'uerSystem'=>[0,1],'printCatId'=>1]);
			return ZHTReturn("提交订单成功", 1,$orderunique);
		}catch (\Exception $e) {
			Db::rollback();
			return ZHTReturn('提交订单失败',-1);
    }
	}
	/**
	 * 计算订单可用积分和金额【积分支付使用】
	 */
	public function allocScoreMoney($carts,$isUseScore,$useScore, $uId=0){
		//计算最大可用积分
		$orderUsableScore = ZHTOrderUsableScore($carts['goodsTotalMoney']-$carts['promotionMoney'],$uId,($isUseScore==1)?1:0,$useScore);
		$useScore = ($useScore>$orderUsableScore['score'])?$orderUsableScore['score']:$useScore;
		$orderScoreMap = [];
		$allocOrderMoney = $orderUsableScore['money'];//积分可兑换的总金额
		$allocOrderScore = $orderUsableScore['score'];//可用积分
		$isLastOrder = false;                      //用来判断是否到最后一个订单
		$totalShop = count($carts['carts']);
		$shopNum = 0;
		foreach ($carts['carts'] as $ckey =>$shopOrder){
			$orderScoreMap[$shopOrder['shopId']]['useMoney'] = 0;
			$orderScoreMap[$shopOrder['shopId']]['useScore'] = 0;
			$shopNum++;
            if($orderUsableScore['money']>0){
				if($shopNum==$totalShop){
					$allocMoney = $allocOrderMoney;
					$allocScore = $allocOrderScore;
				}else{
					$allocMoney = $this->allocOrderMoney($orderUsableScore['money'],$carts['goodsTotalMoney'],$shopOrder['goodsMoney']);
					$allocTmpMoney = $allocOrderMoney - $allocMoney;
					//有可能计算出来金额比实际上还要大，所以要修正一下.
					if($allocTmpMoney<0){
						$allocMoney = $allocOrderMoney;
					}else{
						$allocOrderMoney = $allocTmpMoney;
					}

					$allocScore = ZHTScoreToMoney($allocMoney,true);
                    $allocTmpScore = $allocOrderScore - $allocScore;
					//有可能计算出来金额比实际上还要大，修正分数
					if($allocTmpScore<0){
					    $allocScore = $allocOrderScore;
					}else{
					    $allocOrderScore = $allocTmpScore;
					}
				}
				$orderScoreMap[$shopOrder['shopId']]['useMoney'] = $allocMoney;
				$orderScoreMap[$shopOrder['shopId']]['useScore'] = $allocScore;
			}
		}
		return $orderScoreMap;
	}
	/**
	 * 分配金额和积分
	 */
	public function allocOrderMoney($useMoney,$totalOrderMoney,$orderMoney){
		if($useMoney>$totalOrderMoney)$useMoney = $totalOrderMoney;
    return round(($useMoney*$orderMoney)/$totalOrderMoney,2);
	}
	/**
	 * 根据订单唯一流水获取订单信息
	 */
	public function getByUnique($uId=0,$orderNo=0,$isBatch=0){
		if($orderNo==0){
			$orderNo = input('orderNo');
			$isBatch = (int)input('isBatch/d',1);
		}
		$userId = ($uId==0)?(int)session('ZHT_USER.userId'):$uId;
		if($isBatch==1){
			$rs = $this->where(['userId'=>$userId,'orderunique'=>$orderNo])->field('orderId,orderNo,payType,needPay,orderunique,deliverMoney,userName,userPhone,userAddress')->select();
		}else{
			$rs = $this->where(['userId'=>$userId,'orderNo'=>$orderNo])->field('orderId,orderNo,payType,needPay,orderunique,deliverMoney,userName,userPhone,userAddress')->select();
		}

		$data = [];
		$data['orderunique'] = $orderNo;
		$data['list'] = [];
		$payType = 0;
		$totalMoney = 0;
		$orderIds = [0];
		foreach ($rs as $key =>$v){
			if($v['payType']==1)$payType = 1;
			$totalMoney = $totalMoney + $v['needPay'];
			$orderIds[] = $v['orderId'];
			$data['list'][] = $v;
		}
		$data['totalMoney'] = $totalMoney;
		$data['payType'] = $payType;
		//获取商品信息
		$goods = Db::name('order_goods')->where([['orderId','in',$orderIds]])->select();
		foreach ($goods as $key =>$v){
			// 处理app端
			if($uId>0 && isset($v['goodsTitle'])){
				$v['goodsTitle'] = htmlspecialchars_decode($v['goodsTitle']);
			}
			$shotGoodsSpecTitles = [];
    	 	if($v['goodsSpecTitles']!=""){
    	 		$v['goodsSpecTitles'] = str_replace('：',':',$v['goodsSpecTitles']);
    	 		$goodsSpecTitles = explode('@@_@@',$v['goodsSpecTitles']);

	    	 	foreach ($goodsSpecTitles as $key => $spec) {
	    	 	 	$obj = explode(":",$spec);
	    	 	 	$shotGoodsSpecTitles[] = $obj[1];
	    	 	}
    	 	}
    	 	$v['shotGoodsSpecTitles'] = implode('，',$shotGoodsSpecTitles);

			if($v['goodsSpecTitles']!=''){
				$v['goodsSpecTitles'] = explode('@@_@@',$v['goodsSpecTitles']);
			}else{
				$v['goodsSpecTitles'] = [];
			}
			$data['goods'][$v['orderId']][] = $v;

		}
		//如果是在线支付的话就要加载支付信息
		if($data['payType']==1){
			//获取支付信息
			$payments = model('payment')->where(['isOnline'=>1,'paymentStatus'=>1])->order('dataSort desc')->select();
			$data['payments'] = $payments;
		}
		return $data;
	}
	/**
	 * 检查订单是否已支付
	 */
	public function checkOrderPay2 ($obj){
		$userId = $obj["userId"];
		$orderNo = $obj["orderNo"];
		$isBatch = $obj["isBatch"];
		$rs = array();
		$where = ["userId"=>$userId,"dataFlag"=>1,"orderStatus"=>-2,"isPay"=>0,"payType"=>1];
		if($isBatch==1){
			$where['orderunique'] = $orderNo;
		}else{
			$where['orderNo'] = $orderNo;
		}
		$rs = $this->field('orderId,orderNo')->where($where)->select();
		if(count($rs)>0){
			return ZHTReturn('',1);
		}else{
			return ZHTReturn('订单已支付',-1);
		}
	}
	/**
	 * 获取支付订单信息
	 */
	public function getPayOrders ($obj){
		$userId = (int)$obj["userId"];
		$orderNo = $obj["orderNo"];
		$isBatch = (int)$obj["isBatch"];
		$needPay = 0;
		$where = [["userId",'=',$userId],
				  ["dataFlag",'=',1],
				  ["orderStatus",'=',-2],
				  ["isPay",'=',0],
				  ["payType",'=',1],
				  ["needPay",'>', 0],
				  [($isBatch==1)?'orderunique':'orderNo','=',$orderNo]];
		$data = array();
		$needPay = model('order')->where($where)->sum('needPay');
		$payRand = model('order')->where($where)->max('payRand');
		$data["needPay"] = $needPay;
		$data["payRand"] = $payRand;
		return $data;
	}
	/**
	 * 完成支付订单
	 */
	public function complatePay($obj)	{
		// hook("beforeComplatePay",$obj);

		$trade_no = $obj["trade_no"];
		$isBatch = (int)$obj["isBatch"];
		$orderNo = $obj["out_trade_no"];
		$userId = (int)$obj["userId"];
		$payFrom = $obj["payFrom"];
		$payMoney = (float)$obj["total_fee"];
		if ($payFrom != '') {
			$cnt = model('order')
				->where(['payFrom' => $payFrom, "userId" => $userId, "tradeNo" => $trade_no])
				->count();
			if ($cnt > 0) {
				return ZHTReturn('订单已支付', -1);
			}
		}
		$where = [["userId", "=", $userId], ["dataFlag", "=", 1], ["orderStatus", "=", -2], ["isPay", "=", 0], ["payType", "=", 1]];
		$where[] = ["needPay", ">", 0];
		if ($isBatch == 1) {
			$where[] = ['orderunique', "=", $orderNo];
		} else {
			$where[] = ['orderNo', "=", $orderNo];
		}
		$order = model('order')->where($where)->field('needPay,orderId,orderType,orderNo,shopId,payFrom,realTotalMoney,deliverType,storeId,userPhone')->select();

		if (count($order) == 0) return ZHTReturn('无效的订单信息', -1);
		$needPay = 0;
		foreach ($order as $key => $v) {
			$needPay += $v['needPay'];
		}
		$needPay = ZHTBCMoney($needPay, 0);
		if ($needPay > $payMoney) {
			return ZHTReturn('支付金额不正确', -1);
		}
		Db::startTrans();
		try {
			$data = array();
			$data["needPay"] = 0;
			$data["isPay"] = 1;
			$data["orderStatus"] = 0;
			$data["tradeNo"] = $trade_no;
			$data["payFrom"] = $payFrom;
			$data["payTime"] = date("Y-m-d H:i:s");
			$data["isBatch"] = $isBatch;
			$data["totalPayFee"] = $payMoney * 100;
			$rs = model('order')->where($where)->update($data);

			if ($needPay > 0 && false != $rs) {
				foreach ($order as $key => $v) {
					$orderId = $v["orderId"];

					if ($v['deliverType'] == 1) {
						$verificationCode = ZHTOrderVerificationCode($v->shopId);
						model('order')->where(['orderId' => $orderId])->update(["verificationCode" => $verificationCode]);

						//自提订单（已支付）发送核验码
						// $tpl = ZHTMsgTemplates('PHONE_USER_ORDER_VERIFICATCODE');
						// if ($tpl['tplContent'] != '' && $tpl['status'] == '1') {
						// 	$userPhone = $v->userPhone;
						// 	$storeId = $v->storeId;
						// 	$store = Db::name("stores")->where(["storeId" => $storeId])->field("storeName,storeAddress")->find();
						// 	$storeName = $store["storeName"];
						// 	$storeAddress = $store["storeAddress"];
						// 	$splieVerificationCode = join(" ", str_split($verificationCode, 4));
						// 	$params = ['tpl' => $tpl, 'params' => ['MALL_NAME' => ZHTConf('CONF.mallName'), 'ORDER_CODE' => $splieVerificationCode, 'SHOP_NAME' => $storeName, 'SHOP_ADDRESS' => $storeAddress]];
						// 	model("common/LogSms")->sendSMS(0, $userPhone, $params, 'complatePay', '', $userId, 0);
						// }
					}
					//新增订单日志
					$logOrder = [];
					$logOrder['orderId'] = $orderId;
					$logOrder['orderStatus'] = 0;
					$logOrder['logContent'] = "订单已支付,下单成功";
					$logOrder['logUserId'] = $userId;
					$logOrder['logType'] = 0;
					// $logOrder['logTime'] = date('Y-m-d H:i:s');
					Db::name('log_order')->insert($logOrder);
					//创建一条充值流水记录
					$lm = [];
					$lm['targetType'] = 0;
					$lm['targetId'] = $userId;
					$lm['dataId'] = $orderId;
					$lm['dataSrc'] = 1;
					$lm['remark'] = '交易订单【' . $v['orderNo'] . '】充值¥' . $needPay;
					$lm['moneyType'] = 1;
					$lm['money'] = $needPay;
					$lm['payType'] = $payFrom;
					$lm['tradeNo'] = $trade_no;
					model('log_money')->create($lm);
					//创建一条支出流水记录
					$lm = [];
					$lm['targetType'] = 0;
					$lm['targetId'] = $userId;
					$lm['dataId'] = $orderId;
					$lm['dataSrc'] = 1;
					$lm['remark'] = '交易订单【' . $v['orderNo'] . '】支出¥' . $needPay;
					$lm['moneyType'] = 0;
					$lm['money'] = $needPay;
					$lm['payType'] = 0;
					model('log_money')->create($lm);
					//虚拟商品处理
					if ($v['orderType'] == 1) {
						$this->handleVirtualGoods($v['orderId']);
					} else {
						//发送一条商家信息
						// $tpl = ZHTMsgTemplates('ORDER_HASPAY');
						// if ($tpl['tplContent'] != '' && $tpl['status'] == '1') {
						// 	$find = ['${ORDER_NO}'];
						// 	$replace = [$v['orderNo']];

						// 	$msg = array();
						// 	$msg["shopId"] = $v->shopId;
						// 	$msg["tplCode"] = $tpl["tplCode"];
						// 	$msg["msgType"] = 1;
						// 	$msg["content"] = str_replace($find, $replace, $tpl['tplContent']);
						// 	$msg["msgJson"] = ['from' => 1, 'dataId' => $orderId];
						// 	model("common/MessageQueues")->add($msg);
						// }

						//判断是否需要发送商家短信
						// $tpl = ZHTMsgTemplates('PHONE_SHOP_PAY_ORDER');
						// if ((int)ZHTConf('CONF.smsOpen') == 1 && $tpl['tplContent'] != '' && $tpl['status'] == '1') {

						// 	$params = ['tpl' => $tpl, 'params' => ['ORDER_NO' => $v['orderNo']]];

						// 	$msg = array();
						// 	$tplCode = "PHONE_SHOP_PAY_ORDER";
						// 	$msg["shopId"] = $v->shopId;
						// 	$msg["tplCode"] = $tplCode;
						// 	$msg["msgType"] = 2;
						// 	$msg["paramJson"] = ['CODE' => $tplCode, 'method' => 'complatePay', 'params' => $params];
						// 	$msg["msgJson"] = "";
						// 	model("common/MessageQueues")->add($msg);
						// }
						//微信消息
						// if ((int)ZHTConf('CONF.wxenabled') == 1) {
						// 	$params = [];
						// 	$params['ORDER_NO'] = $v['orderNo'];
						// 	$params['PAY_TIME'] = date('Y-m-d H:i:s');
						// 	$params['MONEY'] = $v['realTotalMoney'];
						// 	$params['PAY_SRC'] = ZHTLangPayFrom($v['payFrom']);

						// 	$msg = array();
						// 	$tplCode = "WX_ORDER_PAY";
						// 	$msg["shopId"] = $v->shopId;
						// 	$msg["tplCode"] = $tplCode;
						// 	$msg["msgType"] = 4;
						// 	$msg["paramJson"] = ['CODE' => $tplCode, 'URL' => Url('wechat/order/sellerorder', '', true, true), 'params' => $params];
						// 	$msg["msgJson"] = "";
						// 	model("common/MessageQueues")->add($msg);
						// }
					}
				}
			} else {
				$data = array();
				$data["userMoney"] = Db::raw("userMoney+" . $payMoney);
				Db::name('user')->where("userId", $userId)->update($data);
				//创建一条充值流水记录
				$lm = [];
				$lm['targetType'] = 0;
				$lm['targetId'] = $userId;
				$lm['dataId'] = $orderNo;
				$lm['dataSrc'] = 1;
				$lm['remark'] = '交易订单充值¥' . $payMoney;
				$lm['moneyType'] = 1;
				$lm['money'] = $payMoney;
				$lm['payType'] = $payFrom;
				$lm['tradeNo'] = $trade_no;
				model('log_money')->create($lm);
			}
			Db::commit();
			// hook("afterOrderPaySuccess",['orderId'=>$orderNo,'isBatch'=>$isBatch,'uerSystem'=>[0,1],'printCatId'=>1]);
			return ZHTReturn('支付成功', 1);
		} catch (\Exception $e) {
			Db::rollback();
			return ZHTReturn('操作失败', -1);
		}
	}
	/**
	 * 获取订单金额以及用户钱包金额
	 */
	public function getOrderPayInfo($obj)	{
		$userId = (int)$obj["userId"];
		$orderNo = $obj["orderNo"];
		$isBatch = (int)$obj["isBatch"];
		$needPay = 0;
		$where = ["userId" => $userId, "dataFlag" => 1, "orderStatus" => -2, "isPay" => 0, "payType" => 1];
		$condition[] = ["needPay", ">", 0];
		if ($isBatch == 1) {
			$where['orderunique'] = $orderNo;
		} else {
			$where['orderNo'] = $orderNo;
		}
		$orders = model('order')->where($where)->where($condition)->field('needPay,payRand')->select();
		if (empty($orders)) return [];
		$needPay = 0;
		$payRand = 0;
		foreach ($orders as $order) {
			$needPay += $order['needPay'];
			if ($payRand < $order['payRand']) $payRand = $order['payRand'];
		}
		$data = array();
		$data["needPay"] = $needPay;
		$data["payRand"] = $payRand;
		return $data;
	}
}